package com.example.skillcinema.adapters

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.paging.PagingDataAdapter
import com.bumptech.glide.Glide
import com.example.skillcinema.R
import com.example.skillcinema.databinding.StaffFilmographyItemBinding
import com.example.skillcinema.db.displaymodels.FilmDisplayModel
import com.example.skillcinema.viewholders.StaffFilmographyViewHolder

class StaffFilmographyPagedAdapter(val onClick: (id: Int) -> Unit) :
    PagingDataAdapter<FilmDisplayModel, StaffFilmographyViewHolder>(DiffUtilCallback()) {
    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): StaffFilmographyViewHolder = StaffFilmographyViewHolder(
        StaffFilmographyItemBinding.inflate(
            LayoutInflater.from(parent.context),
            parent,
            false
        )
    )

    override fun onBindViewHolder(
        holder: StaffFilmographyViewHolder,
        position: Int
    ) {
        val item: FilmDisplayModel? = getItem(position)
        item?.let {
            with(holder.binding) {
                root.setOnClickListener {
                    onClick(item.id)
                }
                ratingTextView.text = item.rate.toString()
                ratingTextView.isVisible = item.rate > 0.0f
                filmNameTextView.text = item.name
                filmInfoTextView.text = item.genre

                Glide.with(filmImageView)
                    .load(item.imageUrl)
                    .placeholder(android.R.drawable.progress_indeterminate_horizontal)
                    .error(android.R.drawable.stat_notify_error)
                    .into(filmImageView)
                if (item.isWatched) {
                    filmImageView.foreground =
                        filmImageView.context.getDrawable(R.drawable.gradient_overlay)
                    seenImageView.visibility = View.VISIBLE
                } else {
                    filmImageView.foreground = null
                    seenImageView.visibility = View.GONE
                }
            }
        }
    }
}